package com.wanqing.controller.user;

import cn.hutool.json.JSONUtil;
import com.wanqing.constant.StatusConstant;
import com.wanqing.entity.Book;
import com.wanqing.result.Result;
import com.wanqing.service.BookService;
import com.wanqing.vo.BookVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userBookController")
@RequestMapping("/user/book")
@Slf4j
@Tag(name = "C端-图书浏览接口")
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据分类id查询图书
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @Operation(summary = "根据分类id查询图书")
    public Result<List<BookVO>> list(Long categoryId) {
        //构造Redis中的key，规则：book_分类id
        String key = "book_" + categoryId;
        //查询Redis中是否存在图书数据
        String jsonBookVO = redisTemplate.opsForValue().get(key);
        //如果存在，直接返回，无需查询数据库
        if (StringUtils.hasText(jsonBookVO)) {
            List<BookVO> list = JSONUtil.toList(jsonBookVO, BookVO.class);
            return Result.success(list);
        }

        Book book = new Book();
        book.setCategoryId(categoryId);
        book.setStatus(StatusConstant.ENABLE);//查询起售中的图书
        //如果不存在，查询数据库，并且将数据存入Redis
        List<BookVO> list = bookService.list(book);
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(list));
        return Result.success(list);
    }

    /**
     * 根据ID查询图书
     *
     * @param id 图书ID
     * @return 图书信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据id查询图书")
    public Result<BookVO> getById(@PathVariable Long id) {
        log.info("根据id查询图书：{}", id);
        BookVO bookVO = bookService.getById(id);
        return Result.success(bookVO);
    }

}